import * as TYPES from '../common/type';
import Global from '../common/global'
import Util from '../common/util'
import Api from "../common/api";

export function logout() {
    return (dispatch) => {
        Global.uid = ''
        Global.storage.remove({
            key : 'user'
        })
        dispatch({
            type: TYPES.LOGOUT
        })
    }
}

export function loginSuccess(user) {
    return (dispatch) => {
        Global.uid = user.uid
        Global.user = user
        dispatch({
            type: TYPES.LOGIN_SUCCESS,
            user: user
        })
        dispatch(getUserInfo())
    }
}


export function loginError() {
    return (dispatch) => {
        Global.uid = "";
        Global.user = {};
        dispatch({
            type: TYPES.LOGIN_ERROR,
        })
    }
}

export function getUserInfo() {
    return (dispatch) => {
        Util.fetchPost(Api.users, {uid : Global.uid})
            .then(({code, msg, data}) => {
                if (code == '0') {
                    dispatch({
                        type: TYPES.UPDATE_USER_INFO,
                        info: {
                            ...data
                        }
                    })
                }
            }).catch(error => {
            console.log(error);
        });

    }
}
